package com.easy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easy.bean.Cart;
import com.easy.bean.Product;
import com.easy.common.CommonResult;
import com.easy.dao.ICartDao;
import com.easy.dao.IProductDao;
import com.easy.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.image.DirectColorModel;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private ICartDao iCartDao;
    @Autowired
    private ICartService iCartService;
    @Autowired
    private IProductDao iProductDao;

    @PostMapping("/add")
    public CommonResult addCart(@RequestParam Integer userId,
                    @RequestParam Integer productId){
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);

        return iCartService.addcart(cart);
    }

    // 查询用户购物车 和当前 商品名称价格
    @GetMapping("/all")
    public CommonResult allCart(@RequestParam Integer userId){
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<Cart> list= iCartDao.selectList(wrapper);
        if(list.isEmpty()){
            return CommonResult.fail("购物车为空");
        }
        // 遍历购物车，查询商品名称和价格
        for(Cart cartItem : list){
            // 假设有商品Dao接口 iProductDao，通过 product_id 查询商品
            Product product = iProductDao.selectById(cartItem.getProductId());
            cartItem.setNowPrice(product.getPrice());
            cartItem.setProductName(product.getProductName());
        }
        return CommonResult.success(list,list.size());
    }

    // 删除购物车商品
    @DeleteMapping("/del")
    public CommonResult delCart(@RequestParam Integer id){
        int result = iCartDao.deleteById(id);
        if (result > 0) {
            return CommonResult.success("删除成功");
        } else {
            return CommonResult.fail("删除失败");
        }
    }

    // 修改购物车商品数量
    @PutMapping("/edit")
    public CommonResult edit(@RequestParam Integer id,
                             @RequestParam Integer num){
        Cart c = iCartDao.selectById(id);
        c.setNum(num);
        int result = iCartDao.updateById(c);
        if (result > 0) {
            return CommonResult.success("商品数量添加成功");
        } else {
            return CommonResult.fail("商品数量添加失败");
        }
    }
}
